package simtester.test

import com.gmongo.GMongo
import com.mongodb.DBRef
import geb.junit4.GebReportingTest;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import simtester.test.pages.*
import simtester.test.Utils

class TestCaseGuiTests extends GebReportingTest {
    static def testConfig
    static def db
    def testusername = 'linh2'
    def testpw = 'linh'
    def testcaseName = 'FunctionalDefaultTest'
    
    @BeforeClass
    static void setUpAll() {
        testConfig = new ConfigSlurper().parse(new File('grails-app/conf/SimTesterConfig.groovy').toURI().toURL())
        db = new GMongo().getDB(testConfig.test.dbname)
        Utils.dropCollections(db)
        
        // Create team Unassigned if not exist
        def team = db.team.findOne(name: 'unassigned')
        if (!team) {
            db.team << [_id: 1L, name: 'unassigned', version: 1L]
        }
    }
    
    @AfterClass
    static void tearDownAll() {
        //Utils.dropCollections(db)
    }
    
    @Before
    public void setUp() throws Exception {
        //db.user << [team: new DBRef(null, 'team', 3L), username: testusername, password: testpw.encodeAsMD5(), adminRole: false, dateCreated: new Date(), lastUpdated: new Date()]
        //def user = db.user.findOne(username: testusername)
        //db.team << [_id: 3L, name: 'svt', users: [new DBRef(null, 'user', user._id)]]
    }
    
    @After
    public void tearDown() throws Exception {
        //db.testCase.remove([:])
        //db.user.remove([:])
        def dirs = new File(testConfig.test.env).listFiles()
        dirs.each {
            new AntBuilder().delete(dir: it)
        }
    }

    @Test
    void addTest() {
        println "team: " + db.team.findOne('unassigned')
        to LoginPage
        assert at(LoginPage)
        $('a', name: 'register').click(RegisterPage)
        
        assert at(RegisterPage)
        registerUser(username: testusername)
        
        assert at(HomePage)
        to LoginPage
        assert at(LoginPage)
        auth.login(testusername, testpw)
        
        to TestRunPage
        assert at(TestRunPage)
        $('#add-test').click()

        // At the add-test wizard, create the test
        File scriptFile
        try {
            scriptFile = new File('testscript.groovy')
            scriptFile.write("some script\ngoes here")
            //waitFor { addTestForm.present }
            addTestForm.name = testcaseName
            addTestForm.script = scriptFile.absolutePath

            $('#add-create').click()
            
            assert at(TestRunPage)
            assert testCasesTable.any {
                it.testname == testcaseName &&
                it.owner    == testusername
            }
        } finally {
            scriptFile.delete()
        }
        
    }

}
